#include "browserhistory.h"
#include <QFile>
#include <QDir>
#include <QDateTime>
#include <QTextStream>

BrowserHistory::BrowserHistory(QWidget *parent) :
	QWidget(parent) {
	// debug
	ui.setupUi(this);

	history_file = new QFile("history_file.qtb");

	if (history_file->exists())
		readFileContent();

	connect(ui.treeWidget, SIGNAL(itemDoubleClicked ( QTreeWidgetItem*, int)),
			this, SLOT(entryClicked(QTreeWidgetItem*, int)));

	/* Exemplo de como operar o arquivo.
	 if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
	 qDebug() << "Open the history file fail.";

	 QTextStream in(&file);
	 while (!in.atEnd()) {
	 QString line = in.readLine();
	 process_line(line);
	 }*/
}

void BrowserHistory::readFileContent() {
	qDebug("reading saved entryes...");
	if (!history_file->open(QIODevice::ReadOnly | QIODevice::Text)) {
		qDebug("Open the history file fail.");
		return;
	}

	QString url;
	uint quando;
	QTextStream read(history_file);
	do {
		read >> url >> quando;

		QTreeWidgetItem *item = new QTreeWidgetItem(ui.treeWidget);
		item->setText(0, url);
		item->setText(1, QDateTime::fromTime_t(quando).toString("dd.MM.yyyy"));
		ui.treeWidget->addTopLevelItem(item);

	} while (!read.atEnd());
	history_file->close();

	history_entrys << url;
}

void BrowserHistory::addHistoryEntry (const QUrl &url) {

	if (!history_file->open(QIODevice::WriteOnly | QIODevice::Text)) {
		qDebug("Open the history file fail.");
		return;
	}

	QTextStream add(history_file);
	add << url.toString() << " " << QDateTime::currentDateTime().toTime_t() << ('\n');
        add.flush();
	history_file->close();

	QTreeWidgetItem *item = new QTreeWidgetItem(ui.treeWidget);
	item->setText(0,url.toString());
	item->setText(1,QDateTime::currentDateTime().toString("dd.MM"));
	ui.treeWidget->addTopLevelItem(item);

	history_entrys << url.toString();
}

bool BrowserHistory::historyContains(const QString& url) const {
	if(history_entrys.contains(url)) return true;
	return false;
}

void BrowserHistory::entryClicked(QTreeWidgetItem * item, int column) {
	Q_UNUSED(column);
	emit historyEntrySelected(QUrl(item->text(0)));
}
